package com.nbicc.news;

import com.nbicc.App;
import com.nbicc.news.mapper.NewsContentMapper;
import com.nbicc.news.po.NewsContent;
import org.dom4j.*;
import org.dom4j.io.SAXReader;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.web.WebAppConfiguration;
import org.xml.sax.InputSource;

import java.io.StringReader;
import java.util.List;

/**
 * @Author: lilingyan
 */
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest(classes=App.class)
@WebAppConfiguration
public class NewsXPath {

    @Autowired
    private NewsContentMapper newsContentMapper;

    @Test
    public void imgSrcParse() throws Exception {
        NewsContent newsContent = newsContentMapper.selectById(1);
        String s = newsContent.getContent();
        s = "<root>" + s + "</root>";
        StringReader read = new StringReader(s);
        SAXReader saxReader = new SAXReader();
        try {
            Document document = saxReader.read(new InputSource(read) );
            List<Element> nodes = document.selectNodes("//img");
            for (Element e : nodes) {
                Attribute src = e.attribute("src");
                System.out.println(src.getValue());
            }
        } catch (DocumentException e) {
            e.printStackTrace();
        }
    }

}
